<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="计划明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="建议租赁商"
                    name="suggest"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="变更历史"
                    name="changeHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                                ref="ruleForm"
                                :rules="rules"
                                class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="年度需用计划：">
                                            <div style="display: flex">
                                                <div>
                                                    {{
                                                        basicForm.annualDemandPlanBillNo
                                                    }}
                                                </div>
                                                <el-button
                                                    class="a"
                                                    @click="clickToYearNeedPlan"
                                                    >查看</el-button
                                                >
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁类型：">
                                            <span>
                                                {{
                                                    basicForm.leaseType == 1
                                                        ? '外租'
                                                        : '内租'
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划日期：">
                                            <span>
                                                {{ basicForm.planDate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="不含税计划金额（元）："
                                        >
                                            <span>
                                                {{
                                                    basicForm.amountExcludingTax
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划金额（元）：">
                                            <span>
                                                {{ basicForm.amount }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报人">
                                            <span>
                                                {{ basicForm.preparer }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税率%：">
                                            <span>
                                                {{ basicForm.taxRate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税额：">
                                            <span>{{
                                                basicForm.taxAmount
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>
                                                {{ basicForm.currency }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{ basicForm.rmbRate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="单据机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                stateArr[basicForm.state]
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <span>{{ basicForm.remarks }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{
                                                basicForm.baseCurName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="本位币汇率：">
                                            <span>{{
                                                basicForm.baseCurRate
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{
                                                basicForm.nullifyCreator
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{
                                                basicForm.nullifyReason
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                basicForm.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                basicForm.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 计划明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">计划明细</div>
                        <div class="e-table">
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <el-table
                                class="table"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                :row-class-name="tableRowClassName"
                                :max-height="$store.state.tableHeight"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    mini-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="需求数量"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                @input="
                                                    curStateChange(
                                                        row,
                                                        'bquantityIsUpdate'
                                                    )
                                                "
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'quantity'
                                                }"
                                                v-model="row.quantity"
                                                clearable
                                                v-if="$index > 0"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="row.quantityIsUpdate"
                                                @clickIcon="
                                                    clickIcon(row.dtlId, 2)
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="degree"
                                    label="新旧程度%"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="租赁单价（元）"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'price'
                                                }"
                                                @input="
                                                    curStateChange(
                                                        row,
                                                        'bpriceIsUpdate'
                                                    )
                                                "
                                                v-model="row.price"
                                                clearable
                                                v-if="$index > 0"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="row.priceIsUpdate"
                                                @clickIcon="
                                                    clickIcon(row.dtlId, 1)
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>

                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="useTime"
                                    label="预计使用时间"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="cost"
                                    label="预计进场费用"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-model="row.cost"
                                                @input="
                                                    curStateChange(
                                                        row,
                                                        'bcostIsUpdate'
                                                    )
                                                "
                                                v-if="$index > 0"
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'cost'
                                                }"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="row.costIsUpdate"
                                                @clickIcon="
                                                    clickIcon(row.dtlId, 3)
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <span v-if="$index > 0">
                                            {{ row.amount }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 建议租赁商 -->
                    <div id="suggestCon" class="con">
                        <div class="tabs-title" id="suggest">建议租赁商</div>
                        <div class="e-table">
                            <el-table
                                class="table"
                                :data="suggestTableData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassName"
                                ref="table"
                                 v-sortTable="{ 'tableData': suggestTableData, '_this': this, 'ref': 'table' }"
                            >
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="材质"
                                    prop="texture"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="leaseOrgName"
                                    label="出租单位"
                                    mini-width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="contactInformation"
                                    label="联系方式"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="canLeaseQuantity"
                                    label="可出租数量"
                                    width="200"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                            isView
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6090"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                    <!-- 变更历史 -->
                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">
                            变更历史
                        </div>
                        <div class="e-table">
                            <el-table
                                :data="changeTableData"
                                border
                                style="width: 100%"
                            >
                                <el-table-column
                                    prop="period"
                                    label="变更期数"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    label="变更编号"
                                    min-width="250"
                                >
                                    <template slot-scope="scope">
                                        <span
                                            style="color: blue"
                                            @click="tableDbShow(scope.row)"
                                            >{{ scope.row.billNo }}</span
                                        >
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="planDate"
                                    label="变更日期"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原计划金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amountChange"
                                    label="变更金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amountChanged"
                                    label="变更后计划金额"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                >
                                    <template slot-scope="scope">
                                        <span>{{
                                            statusLable(scope.row.state)
                                        }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons" v-if="!isview">
            <el-button
                type="primary"
                class="btn-blue"
                v-if="basicForm.state == 2"
                size="small"
                @click="toChengePlanAdd"
                >变更</el-button
            >

            <ComExaButtons
                :auditState="auditState"
                :state="basicForm.state"
                @exas="exas"
                :founderId="basicForm.founderId"
            />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import auditRequest from '@/api/turnover/audit.js'
import { openAppClient, getUuid } from '@/utils/common'
import dataBaseRequest from '@/api/turnover/dataBase.js'
import ComExaButtons from '@/components/common/exaButtons'
import { exas } from '@/pages/revolveMaterialManage/common/revolveCom.js'

import historyUpdateTable from '@/components/common/historyUpdateTable'

import planRequest from '@/api/turnover/plan.js'

import { mapMutations, mapState } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons,
        historyUpdateTable
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        //获取状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                return obj.label
            }
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        })
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'detailed',
            'suggest',
            'attach',
            'auditHistory',
            'changeHistory'
        ]
        this.tabArr = arr //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    created () {
        if (
            this.$route.query.isview === 'true' ||
            this.$route.query.isview === 'false'
        ) {
            this.isview = JSON.parse(this.$route.query.isview)
        }
        this.billId = this.$route.query.billid
        this.getCurrentUnitInfo()
        this.getBasicInfo()
        this.getDicValue()
        this.getDtlList()
        this.getChengeTableData()
        this.getSuggestTableData()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                amount: 0,
                annualDemandPlanBillId: '',
                annualDemandPlanBillNo: '',
                baseCurAmt: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                leaseType: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                period: 0,
                planDate: '',
                preparer: '',
                preparerId: '',
                remarks: '',
                rmbAmt: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                state: 0,
                taxAmount: 0,
                taxRate: 0,
                workId: ''
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            yearNeedPlanList: [],
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6090,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: {
                //作废
                billId: this.$route.query.billid,
                billType: 6090,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            rules: {
                planDate: [
                    {
                        required: true,
                        message: '请输入计划日期',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change' }
                ],
                annualDemandPlanBillId: [
                    {
                        required: true,
                        message: '请选择年度需用计划',
                        trigger: 'change'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请填写税额', trigger: 'blur' }
                ]
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            suggestTableData: [],
            historyTableData: [],
            isview: false,
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setHistoryTableData']),

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        getYearNeedPlanList () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/annualDemandPlan/listByEntity',
                    params: this.query
                })
                .then(res => {
                    this.yearNeedPlanList = res.list
                })
        },
        getSuggestTableData () {
            planRequest
                .turnoverLeasePlanGetSuggestedLessee(this.billId)
                .then(res => {
                    this.suggestTableData = res
                })
        },
        getCurrency () {
            this.$Ajax
                .httpGet({
                    url: '/config/kv/getDicValue',
                    params: {
                        dicName: '币种',
                        dicKey: ''
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    this.currencyArr = res
                })
        },
        //选择币种的事件
        changeCurrency () {
            const obj = this.currencyArr.find(
                item => item.kvKey === this.basicForm.currency
            )
            this.basicForm.currencyId = obj.kvId
        },
        changePlan (val) {
            const obj = this.yearNeedPlanList.find(v => v.billId === val)
            this.basicForm.annualDemandPlanBillNo = obj.billNo
        },

        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/leasePlan/findById',
                    params: {
                        id: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    let arr = this.basicForm.dtls
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                        this.basicForm.dtls = arr
                    }
                })
        },
        clickToYearNeedPlan () {
            let billid = this.basicForm.annualDemandPlanBillId
            if (!billid) {
                this.clientPop('err', '请选择年度需用计划！')
                return
            }
            // 客户端弹窗弹出本地页面
            openAppClient(
                `/yearNeedPlanShow?billid=${billid}&isview=true`,
                '年度需用计划'
            )
        },
        //基础库引入
        clickBaseImpot () {
            alert(1)
            const DownRecursive = async (n1 = 0, n2 = 1) => {
                let res = await dataBaseRequest
                    .materialCategoryLibraryQueryListByParentClassId(n1, n2)
                    .then()
                console.log(res, 'hfadhi ')
                res.forEach(item => {
                    if (item.isDetailed === 0) {
                        DownRecursive(item.billId)
                    }
                    if (item.isDetailed === 1) {
                        this.curMaterialData = item
                        this.doAddChlid()
                    }
                })
            }
            DownRecursive() //向下递归 获取最子级
            // 弹窗选择数据
        },

        //判断当前状态是否已修改
        curStateChange (row, isUpDate) {
            this.curRow = row
            if (row.dtlId) {
                this.curRow.changeType = 2
            }
            if (isUpDate === 'bquantityIsUpdate') {
                this.curRow.bquantityIsUpdate = true
            }
            if (isUpDate === 'bpriceIsUpdate') {
                this.curRow.bpriceIsUpdate = true
            }
            if (isUpDate === 'bcostIsUpdate') {
                this.curRow.bcostIsUpdate = true
            }
            console.log(row)

            this.numYuan(row)
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            planRequest
                .turnoverDtlHistoryGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },
        //小计明细金额
        numYuan (row) {
            // 计算：租赁单价*数量*时间+进场费用
            if (row.quantity && row.price && row.useTime) {
                row.amount = Number(
                    (row.quantity - 0) * (row.price - 0) * (row.useTime - 0) +
                        (row.cost - 0 || 0)
                ).toFixed(2)
            }
            this.collectCount()
            this.onTaxRate()
        },
        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amountExcludingTax = 0
            this.detailedTableData.forEach(v => {

                const count = v.children.reduce(
                    (prev, c) => (prev += Number(c.amount) || 0),
                    0
                )
                this.basicForm.amountExcludingTax = count.toFixed(2)
                v.materialName = `小计： ${count}`
            })
        },
        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate () {
            if (
                this.basicForm.amountExcludingTax != 0 &&
                this.basicForm.taxRate != 0
            ) {
                // 税额
                this.basicForm.taxAmount = Number(
                    (this.basicForm.amountExcludingTax *
                        this.basicForm.taxRate) /
                        100
                ).toFixed(2)

                // 计划金额
                this.basicForm.amount = (
                    Number(this.basicForm.taxAmount) +
                    Number(this.basicForm.amountExcludingTax)
                ).toFixed(2)
            }
        },
        deleteEle (row) {
            row.changeType = -1
        },

        /**
         * 审核
         */
        getDtlList () {
            planRequest
                .turnoverLeasePlanFindDtlByBillId(this.billId)
                .then(res => {
                    res.forEach(item => {
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`

                        item.uuid = getUuid()
                        item.type = this.basicForm.leaseType

                        item.materialClassName = item.topClassName
                        item.children.forEach(v => {
                            v.uuid = getUuid()
                            v.parentId = item.uuid
                        })
                    })

                    this.detailedTableData = res
                    this.collectCount()
                    this.onTaxRate()
                })
        },

        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        planRequest
                            .turnoverLeasePlanUpdate(this.basicForm)
                            .then(() => {
                                this.getBasicInfo() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        planRequest
                            .turnoverLeasePlanUpdateDtl(this.detailedTableData)
                            .then(() => {
                                this.getDtlList() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('detailed')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('detailed')
                        reject(err)
                    })
            })
        },
        submit () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    this.clientPop('err', '保存失败', () => {
                        this.scorllError()
                    })
                })
        },
        /**
         * 下边几个按钮
         */

        async exas (arg) {
            const requestFn = () => {
                return [this.updateBaseInfo(), this.updateBudgetDtl()]
            }
            exas(arg, this, requestFn)
        },
        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/leasePlan/delete',
                    params: { id: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.push('/revolveLeasePlanList')
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if (this.detailedTableData.length > 0) {
                    this.detailedTableData.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (
                                    item.quantity == '' ||
                                    item.quantity == null
                                ) {
                                    let str = `请填写第 ${
                                        index + 1
                                    } 行的需求数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.price == '' || item.price == null) {
                                    let str = `请填写第 ${
                                        index + 1
                                    } 行的租赁单价（元）`
                                    this.errorMsg.push(str)
                                }
                                if (
                                    item.timeUnit == '' ||
                                    item.timeUnit == null
                                ) {
                                    let str = `请填写第 ${
                                        index + 1
                                    } 行的计时单位`
                                    this.errorMsg.push(str)
                                }
                                if (
                                    item.useTime == '' ||
                                    item.useTime == null
                                ) {
                                    let str = `请填写第 ${
                                        index + 1
                                    } 行的预计使用时间`
                                    this.errorMsg.push(str)
                                }
                            }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            } else if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        /**变更历史 */
        //点击查看的时候
        getChengeTableData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/leasePlanChanged/findChangeList',
                    params: {
                        planId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    this.changeTableData = res
                })
        },
        toChengePlanAdd () {
            planRequest
                .turnoverLeasePlanChangedInitData(this.billId)
                .then(() => {
                    this.$router.push({
                        path: '/revolveLeasePlanChengeAdd',
                        query: { billid: this.billId }
                    })
                })
        },
        clickEdit (id) {
            this.$router.push({
                path: '/revolveLeasePlanChengeEdit',
                query: { billid: id }
            })
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //点击进入查看页面
        tableDbShow (row) {
            const billid = row.billId

            if (row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/revolveLeasePlanChengeShow',
                    query: { billid }
                })
            } else {
                // 根据按钮状态来判断点击编辑进什么页面
                const obj = {
                    billId: row.billId,
                    billType: 6091,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                }
                auditRequest.getCurrentUnitInfo(obj).then(res => {
                    this.auditState = res
                    if (this.auditState.canModify) {
                        this.$router.push({
                            path: '/revolveLeasePlanChengeEdit',
                            query: { billid }
                        })
                    } else {
                        this.$router.push({
                            path: '/revolveLeasePlanChengeShow',
                            query: { billid }
                        })
                    }
                })
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}

::v-deep.el-table .cell {
    text-align: center;
}

#iconEdit:hover {
    color: red;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
</style>
